﻿namespace WebAPI.Utils;

using System.Net;
using System.Net.Mail;
using System.Text;

public class MailHelper
{
    /// <summary>
    /// 发送邮件
    /// </summary>
    /// <param name="to">要发送的邮箱</param>
    /// <param name="subject">邮箱主题</param>
    /// <param name="body">邮箱内容</param>
    /// <returns>返回发送邮箱的结果</returns>
    public static bool Send(string to, string subject, string body)
    {
        // 邮件服务设置
        var smtpClient = new SmtpClient();
        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
        smtpClient.Host = "EmailService"; //指定SMTP服务器

        smtpClient.EnableSsl = true;
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = new NetworkCredential("EmailName", "EmailPass");//用户名和密码

        // 发送邮件设置       
        var mailMessage = new MailMessage("EmailName", to); // 发送人和收件人
        mailMessage.Subject = subject;//主题
        mailMessage.Body = body;//内容
        mailMessage.BodyEncoding = Encoding.UTF8;//正文编码
        mailMessage.IsBodyHtml = true;//设置为HTML格式
        mailMessage.Priority = MailPriority.Low;//优先级
        try
        {
            smtpClient.Send(mailMessage); // 发送邮件
            return true;
        }
        catch (SmtpException ex)
        {
            LoggerHelper.Error("邮件发送" + ex.Message);
            return false;
        }
    }
}